package zy.proxy;


import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import zy.service.impl.UserServiceImpl;

import java.lang.reflect.Method;

/**
 * @author LittleDesire
 * @description
 * @date 2022-04-06 周三 10:25
 * @since 17
 */
public class CglibProxy implements MethodInterceptor {

    // 声明目标对象
    private UserServiceImpl target;
    public CglibProxy(UserServiceImpl target) {
        this.target = target;
    }
    /**
     * 对外提供用来创建代理对象的方法
     * @return
     */
    public UserServiceImpl createProxy(){
        // 创建增强器
        Enhancer enhancer = new Enhancer();
        // 指定父类
        enhancer.setSuperclass(UserServiceImpl.class);
        // 指定回调接口对象
        enhancer.setCallback((Callback) this);
        // 返回创建的cglib代理对象
        return (UserServiceImpl) enhancer.create();
    }


    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("q");
        Object res = method.invoke(target, objects[0]);
        System.out.println("h");
        return res;
    }
}
